package com.idp.web.service.impl;

import com.idp.common.base.BaseResult;
import com.idp.common.base.BusinessException;
import com.idp.common.constants.CommonConstants;
import com.idp.common.constants.Constants;
import com.idp.common.persistence.Page;
import com.idp.common.util.OrderCodeUtil;
import com.idp.web.dao.OrdersDao;
import com.idp.web.dto.OrderIndexListDTO;
import com.idp.web.dto.OrderListDTO;
import com.idp.web.entity.*;
import com.idp.web.service.*;
import com.idp.web.vo.DoctorSearchVo;
import com.idp.web.vo.OrderSearchVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 医疗订单service实现类
 *
 * @author xubinren
 * @version 1.0
 * @date 2018/3/6
 */
@Service("ordersService")
public class OrdersServiceImpl implements IOrdersService {

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private IHospitalsService hospitalsService;

    @Resource
    private IDepartmentService departmentService;

    @Resource
    private INurseService nurseService;

    @Resource
    private IHospitalDepartmentService hospitalDepartmentService;

    /**
     * 根据条件分页查询订单列表
     *
     * @param orderSearchVo 查询条件
     * @param page          分页信息
     * @return Page<OrderListDTO>
     */
    @Override
    public Page<OrderListDTO> findByPage(OrderSearchVo orderSearchVo, Page<OrderListDTO> page) {
        page.setResult(ordersDao.selectPage(page,orderSearchVo));
        return page;
    }

    /**
     * 根据条件分页查询订单列表
     *
     * @param orderSearchVo 查询条件
     * @param page          分页信息
     * @return Page<OrderIndexListDTO>
     */
    @Override
    public Page<OrderIndexListDTO> findIndexByPage(OrderSearchVo orderSearchVo, Page<OrderIndexListDTO> page) {
        page.setResult(ordersDao.findIndexByPage(page,orderSearchVo));
        return page;
    }

    /**
     * 查询订单列表
     *
     * @param orders 查询条件
     * @return List<Orders>
     */
    @Override
    public List<Orders> findBySearch(Orders orders) {
        return ordersDao.find(orders);
    }

    /**
     * 通过ID查询
     *
     * @param id 订单id
     * @return Patient
     */
    @Override
    public Orders getById(String id) {
        return ordersDao.getById(id);
    }

    /**
     * 新建订单信息
     *
     * @param orders 订单信息
     * @param userId 操作人id
     * @return BaseResult
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult add(Orders orders,String userId) {

        //数据验证
        if (null == orders
                || StringUtils.isEmpty(orders.getHospitalId())
                || StringUtils.isEmpty(orders.getPatientId())
                || StringUtils.isEmpty(orders.getDepartmentId())
                ){
            return new BaseResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400);
        }

        //医院id
        String hospitalId = orders.getHospitalId().trim();
        //科室id
        String departmentId = orders.getDepartmentId().trim();
        //验证医院下是否存在选择的科室
        HospitalDepartment hospitalDepartment = hospitalDepartmentService.getHospitalDepartment(hospitalId,departmentId);
        if (null == hospitalDepartment){
            return new BaseResult(Constants.RESPONSE_CODE_602,"选择的医院和科室不匹配");
        }
        //医院名称
        Hospitals hospitals = hospitalsService.getById(orders.getHospitalId());
        if (null != hospitals){
            orders.setHospitalName(hospitals.getHospitalName());
        }else {
            return new BaseResult(Constants.RESPONSE_CODE_602,"你选择的医院不存在");
        }

        //科室验证，必须是二级科室
        Department department = departmentService.getById(departmentId);
        if (null == department || CommonConstants.DEPARTMENT_WEIGHT_TWO != department.getWeights()){
            return new BaseResult(Constants.RESPONSE_CODE_607,"选择的科室必须为二级科室");
        }
        orders.setDepartmentName(department.getDepartmentName());

        orders.preInsert(userId);

        //订单编号获取
        String orderCode = OrderCodeUtil.getOrderCode();
        Orders orders1;
        for (int i = CommonConstants.INT_ZERO; i < CommonConstants.INT_TEN; i++) {
            orders1 = ordersDao.getByCode(orderCode);
            if(null == orders1){
                break;
            }
            orderCode = OrderCodeUtil.getOrderCode();

        }

        orders.setOrderCode(orderCode);
        orders.setOrderStatus(CommonConstants.ORDER_STATUS_CONFIRM);

        Integer addNum = ordersDao.add(orders);
        if (null != addNum && addNum > CommonConstants.INT_ZERO){
            return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200);
        }
        return new BaseResult(Constants.RESPONSE_CODE_605,Constants.RESPONSE_MESSAGE_605);
    }

    /**
     * 修改订单信息
     *
     * @param orders 修改后的患者信息
     * @param userId 操作人id
     * @return BaseResult
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult update(Orders orders,String userId) {
        ordersDao.update(orders);
        return null;
    }

    /**
     * 根据患者id删除对应的患者信息
     *
     * @param id 患者id
     * @return boolean
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public boolean delete(String id) {
        ordersDao.delete(id);
        return false;
    }

    /**
     * 查询订单的统计信息
     *
     * @param orderSearchVo 查询条件
     * @return int
     */
    @Override
    public int queryStatistics(OrderSearchVo orderSearchVo){
        int queryNum;
        Integer selectNum = ordersDao.queryStatistics(orderSearchVo);
        if (null == selectNum || selectNum < CommonConstants.INT_ZERO){
            queryNum = CommonConstants.INT_ZERO;
        }else{
            queryNum = selectNum;
        }
        return queryNum;
    }

    /**
     * 查询首页订单的统计信息
     *
     * @param orderSearchVo 查询条件
     * @return int
     */
    @Override
    public int queryIndexStatistics(OrderSearchVo orderSearchVo){
        int queryNum;
        Integer selectNum = ordersDao.queryIndexStatistics(orderSearchVo);
        if (null == selectNum || selectNum < CommonConstants.INT_ZERO){
            queryNum = CommonConstants.INT_ZERO;
        }else{
            queryNum = selectNum;
        }
        return queryNum;
    }


    /**
     *  登录用户为护士时设置医院id
     * @param orderSearchVo 查询条件
     * @param userType 登录用户类型：1、管理员,2、医院，3、护士，4、医生，5、患者
     * @param userId 登录用户的id
     * @return OrderSearchVo
     */
    @Override
    public OrderSearchVo setOrderSearchVo(OrderSearchVo orderSearchVo, Integer userType, String userId){
        if (null == orderSearchVo) {
            orderSearchVo = new OrderSearchVo();
        }

        orderSearchVo = getPageType(orderSearchVo,userType,userId);
        //登录人类型为护士则需要获取对应的医院信息和科室信息
        if (CommonConstants.USER_TYPE_NURSE == userType) {
            Nurse nurse = nurseService.getById(orderSearchVo.getNurseId());
            if (null != nurse){
                orderSearchVo.setHospitalId(nurse.getHospitalId());
                orderSearchVo.setDepartmentId(nurse.getDepartmentId());
            }
        }
        return orderSearchVo;
    }

    /**
     *  设置页面类型
     * @param orderSearchVo 查询条件
     * @param userType 登录用户类型：1、管理员,2、医院，3、护士，4、医生，5、患者
     * @param userId 登录用户的id
     * @return OrderSearchVo
     */
    @Override
    public OrderSearchVo getPageType(OrderSearchVo orderSearchVo, Integer userType, String userId) {
        if (null == orderSearchVo) {
            orderSearchVo = new OrderSearchVo();
        }
        orderSearchVo.setUserId(userId);
        orderSearchVo.setUserType(userType);
        if (CommonConstants.USER_TYPE_HOSPITAL == userType) {
            //国内医院
            orderSearchVo.setHospitalId(userId);
        } else if (CommonConstants.USER_TYPE_NURSE == userType) {
            //护士
            orderSearchVo.setNurseId(userId);
        }
        return orderSearchVo;
    }

    /**
     * 确认订单
     * @param orderSearchVo 订单信息
     * @return BaseResult
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult comfirmOrder(OrderSearchVo orderSearchVo) {
        if (null == orderSearchVo) {
            return new BaseResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400);
        }
        //订单信息获取
        Orders orders = getById(orderSearchVo.getId());
        if (null == orders){
            return new BaseResult(Constants.RESPONSE_CODE_602,Constants.RESPONSE_MESSAGE_602);
        }

        orders.preUpdate(orderSearchVo.getUserId());
        orders.setConfirmTime(orders.getUpdateDate());
        orders.setConfirmUser(orderSearchVo.getUserId());
        orders.setOrderStatus(CommonConstants.ORDER_STATUS_CHECK);

        Integer updateNum = ordersDao.update(orders);
        if (null == updateNum || updateNum < CommonConstants.INT_ONE){
            return new BaseResult(Constants.RESPONSE_CODE_606,Constants.RESPONSE_MESSAGE_606);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 取消订单
     * @param orderSearchVo 订单信息
     * @return BaseResult
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult cancelOrder(OrderSearchVo orderSearchVo) {
        if (null == orderSearchVo) {
            return new BaseResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400);
        }
        //订单信息获取
        Orders orders = getById(orderSearchVo.getId());
        if (null == orders){
            return new BaseResult(Constants.RESPONSE_CODE_602,Constants.RESPONSE_MESSAGE_602);
        }

        orders.preUpdate(orderSearchVo.getUserId());
        orders.setCancelTime(orders.getUpdateDate());
        orders.setCancelUser(orders.getUpdateUser());
        orders.setOrderStatus(CommonConstants.ORDER_STATUS_CANCEL);

        Integer updateNum = ordersDao.update(orders);
        if (null == updateNum || updateNum < CommonConstants.INT_ONE){
            return new BaseResult(Constants.RESPONSE_CODE_606,Constants.RESPONSE_MESSAGE_606);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 分配医生
     *
     * @param doctorSearch 查询信息
     * @return BaseResult
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult assignDoctor(DoctorSearchVo doctorSearch){
        //参数验证
        if (null == doctorSearch || StringUtils.isEmpty(doctorSearch.getOrderId())){
            return new BaseResult(Constants.RESPONSE_CODE_400,Constants.RESPONSE_MESSAGE_400);
        }
        Orders orders = getById(doctorSearch.getOrderId());
        if (null == orders){
            return new BaseResult(Constants.RESPONSE_CODE_602,"订单不存在或已经被删除");
        }

        //订单必须是等待分配的状态
        if (CommonConstants.ORDER_STATUS_ASSIGN != orders.getOrderStatus()){
            return new BaseResult(Constants.RESPONSE_CODE_606,"订单状态不是等待分配，不可被分配");
        }

        orders.preUpdate(doctorSearch.getUserId());
        //状态改为等待方案
        orders.setOrderStatus(CommonConstants.ORDER_STATUS_PROGRAM);
        //分配
        orders.setAllocationTime(orders.getUpdateDate());
        orders.setAllocationUser(doctorSearch.getDoctorId());

        Integer updateNum = ordersDao.update(orders);
        if (null != updateNum && updateNum > CommonConstants.INT_ZERO){
            return new BaseResult(Constants.RESPONSE_CODE_200,Constants.RESPONSE_MESSAGE_200);
        }

        return new BaseResult(Constants.RESPONSE_CODE_606,"分配医生失败");
    }

}